package com.ken.quartz.scheduler;

import com.ken.quartz.job.SimpleTriggerJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.util.Date;

/**
 * 用来测试SimpleTrigger的例子
 * Created by renchongyu on 2018/11/24.
 */
public class SimpleTriggerScheduler {
    public static void main(String[] args) throws Exception{
        Date startDate = new Date();
        Date endDate = new Date();
        //创建一个JobDetail实例，将该实例与HelloJob Class绑定
        JobDetail jobDetail = JobBuilder.newJob(SimpleTriggerJob.class)
                .withIdentity("myJob")
                .build();
        //设置时间
        startDate.setTime(startDate.getTime()+4000l);
        /**
         * 1、创建一个Trigger实例:距离当前时间4秒钟后执行且只执行一次
         *

        SimpleTrigger trigger = (SimpleTrigger)TriggerBuilder.newTrigger()
                .withIdentity("myTrigger","group1")
                .startAt(startDate)
                .build();
         */

        /**
         * 2、创建一个Trigger实例:距离当前时间4秒钟后执行，之后每2秒钟执行一次。
         *
        SimpleTrigger trigger = (SimpleTrigger)TriggerBuilder.newTrigger()
                .withIdentity("myTrigger","group1")
                .startAt(startDate)
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                .withIntervalInSeconds(2))
                .build();
         */

        /**
         * 3、创建一个Trigger实例:距离当前时间4秒钟后执行，之后每2秒钟执行一次执行3次后结束。
         * 若设置了endAt

        SimpleTrigger trigger = (SimpleTrigger)TriggerBuilder.newTrigger()
                .withIdentity("myTrigger","group1")
                .startAt(startDate)
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds(2)
                        .withRepeatCount(2))//从0次开始，3次是2
                .build();
         */

        /**
         * 4、创建一个Trigger实例:距离当前时间4秒钟后执行，之后每2秒钟执行一次执行4次后结束。
         * 若设置了endAt则到时间后即使还有未执行的任务，也要停止。
         */
        endDate.setTime(endDate.getTime()+8000l);
        SimpleTrigger trigger = (SimpleTrigger)TriggerBuilder.newTrigger()
                .withIdentity("myTrigger","group1")
                .startAt(startDate)
                .endAt(endDate)
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds(2)
                        .withRepeatCount(3))//从0次开始，4次是3
                .build();

        //创建Scheduler实例
        SchedulerFactory factory = new StdSchedulerFactory();
        Scheduler scheduler = factory.getScheduler();
        scheduler.start();

        scheduler.scheduleJob(jobDetail,trigger);
    }
}
